package com.javer.web.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.web.context.ContextLoaderListener;

import com.javer.core.SensWordCache;
import com.javer.util.Constants;

public class ApplicationListener extends ContextLoaderListener implements
		ServletContextListener {
	private final Log logger = LogFactory.getLog(getClass());

	@Override
	public void contextInitialized(ServletContextEvent event) {
		String webRoot = event.getServletContext().getRealPath("/");
		System.setProperty("web.root", webRoot);
		
		ServletContext ctx = event.getServletContext();
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss");
		ctx.setAttribute(Constants.StartTime, sdf.format(new Date()));
		
		String configFilename = getClass().getResource("/log4j.properties").toString();
		PropertyConfigurator.configureAndWatch(configFilename, 1000 * 15);
		logger.info("系统日志环境初始化成功");
		logger.info("网站根路径为：" + webRoot);
		
		initSystemData(ctx);
		logger.info("初始化系统数据字典成功");
		
		try {
			SensWordCache.initialize(ctx.getInitParameter(Constants.SensLevel));
			logger.info("初始化系统敏感词成功");
		}
		catch (IOException e) {
			logger.error("初始化系统敏感词失败", e);
		}
		
		super.contextInitialized(event);
		logger.info("初始化Spring容器成功");
	}
	
	protected void initSystemData(ServletContext application) {
		Map<String, String> cbusiness = new HashMap<String, String>();
		cbusiness.put("1", "电信");
		cbusiness.put("2", "银行/金融/保险");
		cbusiness.put("3", "教育");
		cbusiness.put("4", "医疗");
		cbusiness.put("5", "政府");
		cbusiness.put("6", "互联网");
		cbusiness.put("7", "餐饮");
		cbusiness.put("8", "其他");
		application.setAttribute("cbusiness", cbusiness);
		
		Map<String, String> cscale = new HashMap<String, String>();
		cscale.put("10", "10人以下");
		cscale.put("100", "10-100人");
		cscale.put("500", "100-500人");
		cscale.put("1000", "500-1000人");
		cscale.put("-1", "1000人以上");
		application.setAttribute("cscale", cscale);
		
		Map<String, String> articleType = new HashMap<String, String>();
		articleType.put("1", "职场测试");
		articleType.put("2", "职场法案");
		articleType.put("3", "职场健康");
		articleType.put("4", "职场英语");
		articleType.put("5", "骑驴公告");
		articleType.put("6", "公司招聘");
		articleType.put("7", "广告营销");
		articleType.put("8", "友情链接");
		articleType.put("9", "关于我们");
		articleType.put("10", "信息反馈");
		application.setAttribute("articleType", articleType);
	}

}
